package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.Visitor;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@org.springframework.stereotype.Service
public class VisitorApiImpl implements VisitorApi {
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 谁看过我 取前4条记录
     *
     * @param loginUserId
     * @param lastQueryTime
     * @return
     */
    @Override
    public List<Visitor> queryLast4Visitors(Long lastQueryTime, Long loginUserId) {
        //构建条件
        Query query = new Query(Criteria.where("userId").is(loginUserId));
        //是否需要时间条件
        if (null != lastQueryTime) {
            //todo
            //有时间条件
            query.addCriteria(Criteria.where("date").gte(lastQueryTime));
        }
        //按照时间降序
        query.with(Sort.by(Sort.Order.desc("date")));
        //取前四条,前四条记录都是在第一页，skip直接省略
        query.limit(4);
        //直接返回
        List<Visitor> visitorList = mongoTemplate.find(query, Visitor.class);
        //查询登录用户与访客的缘分值
        if (!CollectionUtils.isEmpty(visitorList)) {
            //取出所有访客id
            List<Long> longListId = visitorList.stream().map(Visitor::getVisitorUserId).collect(Collectors.toList());
            //构建推荐表的缘分查询条件
            Query scoreQuery = new Query(Criteria.where("userId").is(longListId).and("toUserId").is(loginUserId));
            //查询推荐表 获取所有的推荐信息
            List<RecommendUser> RecommendUserList = mongoTemplate.find(scoreQuery, RecommendUser.class);
            //转成map key=用户id value=缘分值
            Map<Long, Double> scoreMap = RecommendUserList.stream().collect(Collectors.toMap(RecommendUser::getUserId, RecommendUser::getScore));

            // forEach--操作集合里的每一个元素
            visitorList.forEach(visitor ->
                visitor.setScore(scoreMap.get(visitor.getVisitorUserId())));
        }
        return visitorList;
    }

    /**
     * 保存访客记录
     */
    @Override
    public void save(Visitor visitor) {
        visitor.setDate(System.currentTimeMillis());
        mongoTemplate.save(visitor);
    }
}
